package com.easylinkin.linkappapi.shigongyun.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.alarm.mapper.AlarmMapper;
import com.easylinkin.linkappapi.alarm.vo.AlarmDeviceVo;
import com.easylinkin.linkappapi.config.entity.Config;
import com.easylinkin.linkappapi.config.service.ConfigService;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.elasticsearch.service.IEService;
import com.easylinkin.linkappapi.iaqi.config.IaqiConfigUtil;
import com.easylinkin.linkappapi.machinery.dto.DeviceMachineryDto;
import com.easylinkin.linkappapi.machinery.dto.MachineryIotDeviceDto;
import com.easylinkin.linkappapi.machinery.mapper.ElevatorWorkRecordMapper;
import com.easylinkin.linkappapi.machinery.mapper.MachineryRecordMapper;
import com.easylinkin.linkappapi.machinery.mapper.TowerCraneWorkRecordMapper;
import com.easylinkin.linkappapi.machinery.vo.ElevatorWorkStatisticsVO;
import com.easylinkin.linkappapi.machinery.vo.MachineryDeviceVo;
import com.easylinkin.linkappapi.machinery.vo.TowerCraneWorkStatisticsVO;
import com.easylinkin.linkappapi.ruleengine.entity.RuleEngine;
import com.easylinkin.linkappapi.ruleengine.mapper.RuleEngineMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.shigongyun.service.MachineryMonitorBiService;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author zhengwen
 */
@Service
public class MachineryMonitorBiServiceImpl implements MachineryMonitorBiService {

    private static final String machineryRuleConfigPrefixKey = "RULE_ALARM_MACHINERY_TYPE_";

    private final static String machineryTypeRefConfigStartKey = "MACHINERY_TYPE_";

    @Resource
    private MachineryRecordMapper machineryRecordMapper;

    @Resource
    private DeviceService deviceService;

    @Resource
    private IaqiConfigUtil iaqiConfigUtil;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private AlarmMapper alarmMapper;

    @Resource
    private RuleEngineMapper ruleEngineMapper;

    @Resource
    private ConfigService configService;

    @Override
    public List<MachineryIotDeviceDto> queryMachineryDevices(MachineryDeviceVo machineryDeviceVo) {
        String tenantId = machineryDeviceVo.getTenantId();
        if (StringUtils.isBlank(tenantId)){
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }
        //参数校验
        String typeCode = machineryDeviceVo.getTypeCode();
        Assert.isTrue(StringUtils.isNotBlank(typeCode), "机械设备类型为空");

        machineryDeviceVo.setBinded(1);
        machineryDeviceVo.setTenantId(tenantId);

        List<MachineryIotDeviceDto> ls = machineryRecordMapper.queryMachineryAndDeviceList(machineryDeviceVo);

        //增加关联的设备返回类型(从配置取)
        if (CollectionUtil.isNotEmpty(ls)) {
            Map<String, Map<String, String>> typeUnitMp = new HashMap<>();
            String finalTenantId = tenantId;
            ls.stream().forEach(d -> {
                String machineType = d.getTypeCode();
                Map<String, String> unitMp = typeUnitMp.get(machineType);
                if (unitMp == null) {
                    unitMp = new HashMap<>();
                    String deviceUnitCodeConfigKey = machineryTypeRefConfigStartKey + "" + machineType;
                    Config config = iaqiConfigUtil.getOneConfigs(deviceUnitCodeConfigKey, finalTenantId);
                    if (config != null) {
                        String configVal = config.getValue();
                        JSONArray jsonArray = JSONUtil.parseArray(configVal);
                        unitMp = converConfigTypeMap(jsonArray);
                    }
                    typeUnitMp.put(machineType, unitMp);
                }

                List<DeviceMachineryDto> dmdLs = d.getDeviceList();
                if (CollectionUtil.isNotEmpty(dmdLs)) {
                    String dtc = d.getTypeCode();
                    Map<String, String> mp = typeUnitMp.get(dtc);
                    dmdLs.stream().forEach(dmd -> {
                        String unitTypeName = dmd.getUnitTypeName();
                        if (StringUtils.isNotBlank(unitTypeName)) {
                            String iotType = mp.get(unitTypeName);
                            dmd.setIotType(iotType);
                        } else {
                            dmd.setIotType("unknown");
                        }
                    });
                }
            });
            // 过滤掉不包含main的机械
            ls = ls.stream().filter(p -> {
                List<DeviceMachineryDto> deviceMainList = p.getDeviceList();
                if (CollectionUtil.isEmpty(deviceMainList)) {
                    return false;
                }
                deviceMainList = deviceMainList.stream().filter(d -> "main".equals(d.getIotType())).collect(Collectors.toList());
                return CollectionUtil.isNotEmpty(deviceMainList);
            }).collect(Collectors.toList());
        }

        return ls;
    }

    private Map<String, String> converConfigTypeMap(JSONArray jsonArray) {
        Map<String, String> mp = new HashMap<>();
        if (CollectionUtil.isNotEmpty(jsonArray)) {
            jsonArray.stream().forEach(c -> {
                JSONObject jsonObject = (JSONObject) c;
                String unitTypeName = jsonObject.getStr("unitTypeName");
                String iotType = jsonObject.getStr("iotType");
                mp.put(unitTypeName, iotType);
            });
        }
        return mp;
    }

    @Override
    public RestMessage countMachineryWarnGroupType(MachineryDeviceVo machineryDeviceVo) {
        Date startTime = machineryDeviceVo.getStartTime();
        Date endTime = machineryDeviceVo.getEndTime();
        if (startTime == null || endTime == null) {
            Date now = DateUtil.date();
            startTime = DateUtil.beginOfDay(DateUtil.offsetDay(now, -7));
            endTime = DateUtil.endOfDay(now);
        }
        machineryDeviceVo.setStartTime(startTime);
        machineryDeviceVo.setEndTime(endTime);

        String tenantId = machineryDeviceVo.getTenantId();
        if (StringUtils.isBlank(tenantId)) {
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }

        /*//查询设备电子档案
        String typeCode = machineryDeviceVo.getTypeCode();

        String configKey = machineryRuleConfigPrefixKey + typeCode;

        Config config = iaqiConfigUtil.getOneConfigs(configKey, tenantId);
        Assert.notNull(config, "电子档案设备类型" + typeCode + "缺少报警规则配置信息");

        //从配置获取
        String configVal = config.getValue();

        //配置转换
        JSONArray jsonArray = JSONUtil.parseArray(configVal);
        List<String> ruleIds = converConfigToRuleIdList(jsonArray);

        AlarmDeviceVo alarmDeviceVo = converConfigAlarmDeviceVo(ruleIds, machineryDeviceVo, tenantId);

        //查询统计
        List<Map<String, Object>> alarmMap = alarmMapper.countAlarmByRule(alarmDeviceVo);


        //数据转换
        Map<String, Object> dataMp = new HashMap<>();
        if (CollectionUtil.isNotEmpty(alarmMap)) {
            alarmMap.stream().forEach(d -> {
                Object ruleId = d.get("ruleId");
                if (ruleId != null) {
                    dataMp.put(ruleId.toString(), d.get("num"));
                }
            });
        }

        //数据补全
        List<Map<String, Object>> alarmMapLs = new ArrayList<>();
        jsonArray.stream().forEach(d -> {
            JSONObject jsonObject = (JSONObject) d;
            Object ruleIdObj = jsonObject.get("ruleId");
            Object alarmNameObj = jsonObject.get("alarmName");
            if (ruleIdObj != null) {
                Map<String, Object> cmp = new HashMap<>();
                Object numObj = dataMp.get(ruleIdObj.toString());
                if (numObj == null) {
                    cmp.put("ruleId", ruleIdObj.toString());
                    cmp.put("alarmName", jsonObject.getStr("alarmName"));
                    cmp.put("num", 0);
                } else {
                    cmp.put("ruleId", ruleIdObj.toString());
                    cmp.put("alarmName", alarmNameObj.toString());
                    cmp.put("num", numObj.toString());
                }
                alarmMapLs.add(cmp);
            }
        });
        return RestBuilders.successBuilder().data(alarmMapLs).build();*/

        String typeCode = machineryDeviceVo.getTypeCode();
        String deviceUnitCodeConfigKey = machineryTypeRefConfigStartKey + "" + typeCode;

        AtomicReference<Config> config = new AtomicReference<>(iaqiConfigUtil.getOneConfigs(deviceUnitCodeConfigKey, tenantId));
        if (config.get() == null || StringUtils.isBlank(config.get().getValue())) {
            //这里先不报友好提示了，直接复制插入默认的配置
            //return RestBuilders.errorBuilder().message("缺少电子档案关联IOT设备配置").build();
            //20221011变更
            Config configEx = new Config(deviceUnitCodeConfigKey);
            configEx.setTenantId(null);
            List<Config> defConfLs = configService.selectList(configEx, true);
            if (CollectionUtil.isNotEmpty(defConfLs)) {
                String finalTenantId = tenantId;
                defConfLs.stream().forEach(dc -> {
                    if(StringUtils.isBlank(dc.getTenantId())){
                        dc.setId(null);
                        dc.setTenantId(finalTenantId);
                        dc.setCreateTime(DateUtil.date());
                        dc.setModifyTime(dc.getCreateTime());
                        configService.save(dc);
                        config.set(dc);
                    }
                });
            } else {
                return RestBuilders.errorBuilder().message("缺少电子档案关联IOT设备默认配置").build();
            }
        }
        String configVal = config.get().getValue();
        JSONArray jsonArray = JSONUtil.parseArray(configVal);
        if (CollectionUtil.isEmpty(jsonArray)) {
            return RestBuilders.errorBuilder().message("缺少电子档案关联IOT设备配置").build();
        }

        List<String> deviceTypeNameList = converConfigToUnitTypeNameList(jsonArray);

        AlarmDeviceVo alarmDeviceVo = new AlarmDeviceVo();
        alarmDeviceVo.setTenantId(tenantId);
        alarmDeviceVo.setStartTime(machineryDeviceVo.getStartTime());
        alarmDeviceVo.setEndTime(machineryDeviceVo.getEndTime());
        alarmDeviceVo.setDeviceTypeNameList(deviceTypeNameList);
        if (null != machineryDeviceVo.getDevice()) {
            alarmDeviceVo.setDeviceInfo(machineryDeviceVo.getDevice());
        }

        List<Map<String, Object>> alarmMapLs = alarmMapper.countAlarmByRuleAndParamGlobal(alarmDeviceVo);

        //20221010增加补全数据
        //1根据租户id、规则类型、规则名称前缀
        String prefixName = "";
        switch (typeCode) {
            case "QUIP_TSQZJ_01":
                prefixName = "塔吊-";
                break;
            case "QUIP_SJJ_02":
                prefixName = "升降机-";
                break;
            default:
                break;
        }
        QueryWrapper<RuleEngine> reqw = new QueryWrapper<>();
        reqw.eq("tenant_id", tenantId);
        reqw.likeRight(StringUtils.isNotBlank(prefixName), "name", prefixName);
        List<RuleEngine> ruleEngineList = ruleEngineMapper.selectList(reqw);
        //数据转换补全
        List<Map<String, Object>> finAlarmMapLs = converAndCompAlarmData(ruleEngineList, alarmMapLs);

        return RestBuilders.successBuilder().data(finAlarmMapLs).build();
    }

    /**
     * 转换出参
     *
     * @param ruleEngineList 规则配置list
     * @param alarmMapLs     报警数据
     * @return 最终告警数据
     */
    private List<Map<String, Object>> converAndCompAlarmData(List<RuleEngine> ruleEngineList, List<Map<String, Object>> alarmMapLs) {
        List<Map<String, Object>> mpLs = new ArrayList<>();
        Map<String, Map<String, Object>> ruleEngineMp = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ruleEngineList)) {
            ruleEngineList.stream().forEach(p -> {
                Map<String, Object> mp = new HashMap<>();
                mp.put("rule_engine_id", p.getId());
                mp.put("alarmName", p.getName());
                mp.put("num", 0);
                ruleEngineMp.put(p.getId(), mp);
            });
        }
        if (CollectionUtil.isNotEmpty(alarmMapLs)) {
            alarmMapLs.stream().forEach(m -> {
                String key = m.get("rule_engine_id").toString();
                Map<String, Object> mp = ruleEngineMp.get(key);
                if (mp != null) {
                    mp.put("num", m.get("num"));
                } else {
                    mp = m;
                }
                ruleEngineMp.put(key, mp);
            });
        }
        //最后遍历一遍处理名称
        if (CollectionUtil.isNotEmpty(ruleEngineMp)) {
            ruleEngineMp.values().stream().forEach(r -> {
                String alarmName = r.get("alarmName").toString();
                if (StringUtils.isNotBlank(alarmName) && alarmName.indexOf("-") > 0) {
                    String[] alarmNameArr = alarmName.split("-");
                    r.put("alarmName", alarmNameArr[1]);
                }
                mpLs.add(r);
            });
        }
        return mpLs;
    }


    @Override
    public RestMessage countMachineryWarnByDay(MachineryDeviceVo machineryDeviceVo) {
        Date startTime = machineryDeviceVo.getStartTime();
        Date endTime = machineryDeviceVo.getEndTime();
        if (startTime == null || endTime == null) {
            Date now = DateUtil.date();
            startTime = DateUtil.beginOfDay(DateUtil.offsetDay(now, -31));
            endTime = DateUtil.endOfDay(DateUtil.offsetDay(now, -1));
        }
        machineryDeviceVo.setStartTime(startTime);
        machineryDeviceVo.setEndTime(endTime);

        String tenantId = machineryDeviceVo.getTenantId();
        if (StringUtils.isBlank(tenantId)) {
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }

        /*//查询设备电子档案
        String typeCode = machineryDeviceVo.getTypeCode();

        String configKey = machineryRuleConfigPrefixKey + typeCode;

        //从配置获取
        Config config = iaqiConfigUtil.getOneConfigs(configKey, tenantId);
        Assert.notNull(config, "电子档案设备类型" + typeCode + "缺少报警规则配置信息");

        String configVal = config.getValue();
        //配置转换
        JSONArray jsonArray = JSONUtil.parseArray(configVal);
        List<String> ruleIds = converConfigToRuleIdList(jsonArray);

        AlarmDeviceVo alarmDeviceVo = converConfigAlarmDeviceVo(ruleIds, machineryDeviceVo, tenantId);

        //查询统计
        List<Map<String, Object>> alarmMap = alarmMapper.countAlarmByDay(alarmDeviceVo);*/
        String typeCode = machineryDeviceVo.getTypeCode();
        String deviceUnitCodeConfigKey = machineryTypeRefConfigStartKey + "" + typeCode;

        Config config = iaqiConfigUtil.getOneConfigs(deviceUnitCodeConfigKey, tenantId);
        if (config == null || StringUtils.isBlank(config.getValue())) {
            return RestBuilders.errorBuilder().message("缺少电子档案关联IOT设备配置").build();
        }
        String configVal = config.getValue();
        JSONArray jsonArray = JSONUtil.parseArray(configVal);
        if (CollectionUtil.isEmpty(jsonArray)) {
            return RestBuilders.errorBuilder().message("缺少电子档案关联IOT设备配置").build();
        }

        List<String> deviceTypeNameList = converConfigToUnitTypeNameList(jsonArray);

        AlarmDeviceVo alarmDeviceVo = new AlarmDeviceVo();
        alarmDeviceVo.setTenantId(tenantId);
        alarmDeviceVo.setStartTime(machineryDeviceVo.getStartTime());
        alarmDeviceVo.setEndTime(machineryDeviceVo.getEndTime());
        alarmDeviceVo.setDeviceTypeNameList(deviceTypeNameList);
        if (null != machineryDeviceVo.getDevice()) {
            alarmDeviceVo.setDeviceInfo(machineryDeviceVo.getDevice());
        }
        List<Map<String, Object>> alarmMap = alarmMapper.countAlarmByDayAndParamGlobal(alarmDeviceVo);

        //数据补全
        TreeMap<String, Object> alarmMapTree = compAlarmDayCountData(alarmMap, machineryDeviceVo);

        return RestBuilders.successBuilder().data(alarmMapTree).build();
    }

    /**
     * @param jsonArray
     * @return
     */
    private List<String> converConfigToUnitTypeNameList(JSONArray jsonArray) {
        List<String> unitCodeLs = jsonArray.stream().map(e -> {
            JSONObject jsonObject = (JSONObject) e;
            if (jsonObject.containsKey("iotType") && jsonObject.containsKey("unitTypeName")) {
                String iotType = jsonObject.getStr("iotType");
                if ("main".equals(iotType)) {
                    return jsonObject.getStr("unitTypeName");
                }
                return null;
            } else {
                return null;
            }
        }).collect(Collectors.toList());
        return unitCodeLs;
    }

    /**
     * 补全报警日统计
     *
     * @param alarmMap
     * @param machineryDeviceVo
     * @return
     */
    private TreeMap<String, Object> compAlarmDayCountData(List<Map<String, Object>> alarmMap, MachineryDeviceVo machineryDeviceVo) {
        Map<String, String> mp = new HashMap<>();
        alarmMap.stream().forEach(c -> {
            Object alarmTimeObj = c.get("alarmTime");
            Object numObj = c.get("num");
            if (alarmTimeObj != null) {
                mp.put(alarmTimeObj.toString(), numObj.toString());
            }
        });

        TreeMap<String, Object> alarmMapTree = new TreeMap<>();
        Date startTime = machineryDeviceVo.getStartTime();
        Date endTime = machineryDeviceVo.getEndTime();
        while (startTime.before(endTime)) {
            String ymd = DateUtil.format(startTime, DatePattern.NORM_DATE_FORMAT);
            String num = mp.get(ymd);
            if (StringUtils.isBlank(num)) {
                num = "0";
            }
            alarmMapTree.put(ymd, num);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        return alarmMapTree;
    }


    /**
     * @param jsonArray
     * @return
     */
    private List<String> converConfigToRuleIdList(JSONArray jsonArray) {
        List<String> ruleIds = jsonArray.stream().map(e -> {
            JSONObject jsonObject = (JSONObject) e;
            if (((JSONObject) e).containsKey("ruleId")) {
                return jsonObject.getStr("ruleId");
            } else {
                return null;
            }
        }).collect(Collectors.toList());
        return ruleIds;
    }

    /**
     * @param ruleIds
     * @param machineryDeviceVo
     * @param tenantId
     * @return
     */
    private AlarmDeviceVo converConfigAlarmDeviceVo(List<String> ruleIds, MachineryDeviceVo machineryDeviceVo, String tenantId) {
        //入参转换
        AlarmDeviceVo alarmDeviceVo = new AlarmDeviceVo();
        alarmDeviceVo.setDeviceInfo(machineryDeviceVo.getDevice());
        alarmDeviceVo.setStartTime(machineryDeviceVo.getStartTime());
        alarmDeviceVo.setEndTime(machineryDeviceVo.getEndTime());
        alarmDeviceVo.setTenantId(tenantId);
        alarmDeviceVo.setRuleIds(ruleIds);
        return alarmDeviceVo;
    }

    @Autowired
    private IEService ieService;

    @Autowired
    private LinkappTenantService linkappTenantService;

    @Resource
    private TowerCraneWorkRecordMapper towerCraneWorkRecordMapper;

    @Resource
    private ElevatorWorkRecordMapper elevatorWorkRecordMapper;

    @Override
    public RestMessage countMachineryOperationToday(MachineryDeviceVo machineryDeviceVo) {
        Long countTodayOperation = 0l;
        //参数校验
        String typeCode = machineryDeviceVo.getTypeCode();
        Assert.isTrue(StringUtils.isNotBlank(typeCode), "机械设备类型为空");

//        machineryDeviceVo.setBinded(1);
//
//        List<MachineryIotDeviceDto> ls = machineryRecordMapper.queryMachineryAndDeviceList(machineryDeviceVo);
//
//        List<DeviceMachineryDto> deviceAllList = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(ls)) {
//            for (MachineryIotDeviceDto p : ls) {
//                List<DeviceMachineryDto> deviceList = p.getDeviceList();
//                if (CollectionUtil.isNotEmpty(deviceList)) {
//                    deviceAllList.addAll(deviceList);
//                }
//            }
//        }
        List<String> deviceCodes = null;
        if(null != machineryDeviceVo.getDevice()){
            deviceCodes = Arrays.asList(machineryDeviceVo.getDevice().getCode());
        }
        if (CollectionUtil.isNotEmpty(deviceCodes)) {

            String tenantId = machineryDeviceVo.getTenantId();
            if (StringUtils.isBlank(tenantId)) {
                tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
            }
            if("QUIP_TSQZJ_01".equals(typeCode)){
                TowerCraneWorkStatisticsVO reqVO = new TowerCraneWorkStatisticsVO();
                reqVO.setCodeList(deviceCodes);
                reqVO.setTenantId(tenantId);
                reqVO.setStartTime(com.easylinkin.linkappapi.common.utils.DateUtil
                    .getYYYYMMDDHHMMSSDate(com.easylinkin.linkappapi.common.utils.DateUtil.getCurrentDayMixDate()));
                reqVO.setEndTime(com.easylinkin.linkappapi.common.utils.DateUtil
                    .getYYYYMMDDHHMMSSDate(com.easylinkin.linkappapi.common.utils.DateUtil.getCurrentDayMaxDate()));
                TowerCraneWorkStatisticsVO statisticsSum2 = towerCraneWorkRecordMapper
                    .getStatisticsSum(reqVO);
                if (null != statisticsSum2) {
                    countTodayOperation = statisticsSum2.getWorkCount().longValue();
                }
            }
            if("QUIP_SJJ_02".equals(typeCode)){
                ElevatorWorkStatisticsVO reqVO = new ElevatorWorkStatisticsVO();
                reqVO.setCodeList(deviceCodes);
                reqVO.setTenantId(tenantId);
                reqVO.setStartTime(com.easylinkin.linkappapi.common.utils.DateUtil
                    .getYYYYMMDDHHMMSSDate(com.easylinkin.linkappapi.common.utils.DateUtil.getCurrentDayMixDate()));
                reqVO.setEndTime(com.easylinkin.linkappapi.common.utils.DateUtil
                    .getYYYYMMDDHHMMSSDate(com.easylinkin.linkappapi.common.utils.DateUtil.getCurrentDayMaxDate()));
                ElevatorWorkStatisticsVO statisticsSum2 = elevatorWorkRecordMapper
                    .getStatisticsSum(reqVO);
                if (null != statisticsSum2) {
                    countTodayOperation = statisticsSum2.getWorkCount().longValue();
                }
            }

        }
        return RestBuilders.successBuilder().data(countTodayOperation).build();
    }

    @Override
    public RestMessage countMachineryOperation(MachineryDeviceVo machineryDeviceVo) {
        Long countTodayOperation = 0l;
        //参数校验
        String typeCode = machineryDeviceVo.getTypeCode();
        Assert.isTrue(StringUtils.isNotBlank(typeCode), "机械设备类型为空");

        List<String> deviceCodes = null;
        if(null != machineryDeviceVo.getDevice()){
            deviceCodes = Arrays.asList(machineryDeviceVo.getDevice().getCode());
        }
        if (CollectionUtil.isNotEmpty(deviceCodes)) {

            String tenantId = machineryDeviceVo.getTenantId();
            if (StringUtils.isBlank(tenantId)) {
                tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
            }
            if("QUIP_TSQZJ_01".equals(typeCode)){
                TowerCraneWorkStatisticsVO reqVO = new TowerCraneWorkStatisticsVO();
                reqVO.setCodeList(deviceCodes);
                reqVO.setTenantId(tenantId);
                reqVO.setStartTime(machineryDeviceVo.getJoinStartTime());
                reqVO.setEndTime(machineryDeviceVo.getJoinEndTime());
                TowerCraneWorkStatisticsVO statisticsSum2 = towerCraneWorkRecordMapper
                        .getStatisticsSum(reqVO);
                if (null != statisticsSum2) {
                    countTodayOperation = statisticsSum2.getWorkCount().longValue();
                }
            }

        }
        return RestBuilders.successBuilder().data(countTodayOperation).build();
    }

    @Override
    public List<MachineryIotDeviceDto> selectMachineryAndDeviceByCondition(
            MachineryDeviceVo machineryDeviceVo) {
        String tenantId = machineryDeviceVo.getTenantId();
        String typeCode = machineryDeviceVo.getTypeCode();
        String deviceUnitCodeConfigKey = machineryTypeRefConfigStartKey + "" + typeCode;
        Config config = iaqiConfigUtil.getOneConfigs(deviceUnitCodeConfigKey, tenantId);
        if (config == null || StringUtils.isBlank(config.getValue())) {
            throw new RuntimeException("缺少电子档案关联IOT设备配置");
        }
        String configVal = config.getValue();
        JSONArray jsonArray = JSONUtil.parseArray(configVal);
        if (CollectionUtil.isEmpty(jsonArray)) {
            throw new RuntimeException("缺少电子档案关联IOT设备配置");
        }
        List<String> deviceTypeNameList = converConfigToUnitTypeNameList(jsonArray);
        machineryDeviceVo.setDeviceTypeNameList(deviceTypeNameList);
        List<MachineryIotDeviceDto> allMachineryIotDeviceDtos = machineryRecordMapper
                .selectMachineryAndDeviceByConditionGlobal(machineryDeviceVo);
        if (CollectionUtil.isNotEmpty(allMachineryIotDeviceDtos)) {
            return allMachineryIotDeviceDtos;
        } else {
            return null;
        }
    }
}
